package main;

import net.minecraft.server.v1_14_R1.NBTBase;
import net.minecraft.server.v1_14_R1.NBTTagCompound;
import net.minecraft.server.v1_14_R1.NBTTagString;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.craftbukkit.v1_14_R1.inventory.CraftItemStack;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.bukkit.Bukkit.createBlockData;

public class Main extends JavaPlugin implements Listener {
    private FileConfiguration config;
    private boolean enable;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        config = getConfig();
        saveConfig();
        enable = config.getBoolean("enable");

        Bukkit.getPluginManager().registerEvents(this, this);
        this.getCommand("e").setExecutor(this);
        this.getCommand("ek").setExecutor(this);
        this.getCommand("ekd").setExecutor(this);
        this.getCommand("enkindle").setExecutor(this);
        this.getCommand("enkindle").setTabCompleter(this);
        Bukkit.getConsoleSender().sendMessage("§e[Enkindle]§f启用成功，输入§b/enkindle help§f以查看更多信息。");
        Bukkit.getConsoleSender().sendMessage("§e[Enkindle]§fEnkindle插件当前默认为" + (enable ? "§f[§a启用§f]" : "§f[§4停用§f]。")+"状态");
    }

    @Override
    public void onDisable() {
        Bukkit.getConsoleSender().sendMessage("§e[Enkindle]§f卸载成功。");
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
        String[] enkindle = {"help", "check", "enable", "disable"};
        if (args.length > 1)
            return new ArrayList<>();
        if (args.length == 0)
            return Arrays.asList(enkindle);
        return Arrays.stream(enkindle).filter(s -> s.startsWith(args[0])).collect(Collectors.toList());
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String s, String[] args) {
        if (sender.hasPermission("minecraft")) {
            if (args.length == 0) {
                args = new String[]{"help"};
            }
            switch (getCmd(args[0])) {
                case "help":
                    sender.sendMessage(new String[]{
                            "§e==============[Enkindle]=============",
                            "§e/enkindle help§f - 获取帮助",
                            "§e/enkindle check§f - 检查插件状态",
                            "§e/enkindle enable§f - 启用插件",
                            "§e/enkindle disable§f - 停用插件",
                            "§e====================================="
                    });
                    return true;
                case "check":
                    sender.sendMessage("§eEnkindle插件已" + (enable ? "§f[§a启用§f]" : "§f[§4停用§f]"));
                    return true;
                case "enable":
                    if (enable) {
                        sender.sendMessage("§eEnkindle插件已是§a启用§e状态");
                    } else {
                        enable = true;
                        sender.sendMessage("§eEnkindle插件已" + (enable ? "§f[§a启用§f]" : "§f[§4停用§f]"));
                    }
                    return true;
                case "disable":
                    if (enable) {
                        enable = false;
                        sender.sendMessage("§eEnkindle插件已" + (enable ? "§f[§a启用§f]" : "§f[§4停用§f]"));
                    } else {
                        sender.sendMessage("§eEnkindle插件已是§4停用§e状态");
                    }
                    return true;
            }
            sender.sendMessage("§4[Enkindle]§f该指令不存在。");
            return true;
        }
        sender.sendMessage("§4[Enkindle]§f您没有权限使用该指令。");
        return true;
    }

    @EventHandler
    public void onEvent(PlayerInteractEvent e) {
        if (enable && e.getPlayer().isSneaking() && e.hasItem() && e.hasBlock()) {
            Player player = e.getPlayer();
            ItemStack item = e.getItem();
            Block block = e.getClickedBlock();
            String itemType = getItemType(item.getType(), block.getType());
            String actionType = getActionType(item.getType(), block.getType());
            if (!(itemType.equals("") || actionType.equals(""))) {
                String blockdata = block.getBlockData().getAsString();
                String data = blockdata.substring(blockdata.indexOf('['), blockdata.indexOf(']') + 1);
                if (actionType.equals("lit")) {
                    block.setBlockData(createBlockData(block.getType(), data.replace("lit=false", "lit=true")));
                }
                if (actionType.equals("face")) {
                    boolean flag = true;
                    String face = "";
                    String[] faces = new String[]{"east", "south", "west", "north"};
                    String[] facing = new String[]{"facing=east", "facing=south", "facing=west", "facing=north"};
                    for (int i = 0; i < 4; i++)
                        if (e.getBlockFace().toString().equalsIgnoreCase(faces[i]))
                            face = faces[i];
                    if (!face.equals(""))
                        for (int i = 0; i < 4; i++)
                            if (flag && data.indexOf(facing[i]) > -1) {
                                block.setBlockData(createBlockData(block.getType(), data.replace(facing[i], "facing=" + face)));
                                flag = false;
                            }
                }
                if (actionType.equals("fence")) {
                    boolean flag = true;
                    String face = "";
                    String[] faces = new String[]{"east", "south", "west", "north"};
                    String[] linkTrue = new String[]{"east=true", "south=true", "west=true", "north=true"};
                    String[] linkFalse = new String[]{"east=false", "south=false", "west=false", "north=false"};
                    for (int i = 0; i < 4; i++)
                        if (e.getBlockFace().toString().equalsIgnoreCase(faces[i]))
                            face = faces[i];
                    if (!face.equals(""))
                        for (int i = 0; i < 4; i++)
                            if (flag && linkTrue[i].indexOf(face) > -1) {
                                if (data.indexOf(linkTrue[i]) > -1)
                                    block.setBlockData(createBlockData(block.getType(), data.replace(linkTrue[i], linkFalse[i])));
                                else
                                    block.setBlockData(createBlockData(block.getType(), data.replace(linkFalse[i], linkTrue[i])));
                                flag = false;
                            }
                }
                if (itemType.equals("tool")) {
                    e.setCancelled(true);
                }
                if (itemType.equals("consumables")) {
                    item.setAmount(item.getAmount() - 1);
                    e.setCancelled(true);
                }
            }
        }
    }

    private String getItemType(Material item, Material block) {
        String[] itemType = new String[]{"tool", "consumables"};
        String[] actionType = new String[]{"lit", "face", "fence"};
        for (int i = 0; i < 3; i++)
            for (String blockName : config.getStringList(actionType[i] + ".block"))
                if (block.toString().equalsIgnoreCase(blockName))
                    for (int j = 0; j < 2; j++)
                        for (String itemName : config.getStringList(actionType[i] + ".item." + itemType[j]))
                            if (item.toString().equalsIgnoreCase(itemName))
                                return itemType[j];
        return "";
    }

    private String getActionType(Material item, Material block) {
        String[] itemType = new String[]{"tool", "consumables"};
        String[] actionType = new String[]{"lit", "face", "fence"};
        for (int i = 0; i < 3; i++)
            for (String blockName : config.getStringList(actionType[i] + ".block"))
                if (block.toString().equalsIgnoreCase(blockName))
                    for (int j = 0; j < 2; j++)
                        for (String itemName : config.getStringList(actionType[i] + ".item." + itemType[j]))
                            if (item.toString().equalsIgnoreCase(itemName))
                                return actionType[i];
        return "";
    }

    private String getCmd(String str) {
        List<String[]> list = new ArrayList();
        list.add(new String[]{"?", "help"});
        list.add(new String[]{"!", "check"});
        list.add(new String[]{"on", "open", "enable"});
        list.add(new String[]{"off", "close", "disable"});
        for (String[] strs : list) {
            if (checkCmd(str, strs))
                return strs[strs.length - 1];
        }
        return "";
    }

    private boolean checkCmd(String param, String[] list) {
        for (String temp : list) if (param.equalsIgnoreCase(temp)) return true;
        return false;
    }

}
